iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
Software Development

玩轉C# 進階學習之旅系列 第 8

玩轉C#之【反射 Reflection 射爆妳】

  • 分享至 

  • xImage
  •  

介紹

反射:System.Reflection .Net框架提供的Library,可以讀取並使用metadata

Dll-IL-Metadata-反射


人類在開發的時候寫的是高級語言C#,最終會變成機械碼
在.net framework有二次編譯的概念,二次編譯,為了不同平台上使用,加上一層中間層,更靈活

  1. 透過VS編譯器 編譯成dll/exe
  2. 點擊exe的時候,他有一個依賴的環境叫做CLR

dll/exe裡面包含兩大塊IL(中間語言),metadata(元數據)

metadata會紀錄這dll/exe裡面有哪些東西<=反射主要在做這塊

IL:可以透過ILSpy(反編譯工具)
ILSpy

反射+屬性(Property/Field)

public class People
{
    public People()
    {
        Console.WriteLine("{0}",this.GetType().FullName);
    }
    public int Id{get;set;}//Property
    
    public string Name{get;set;}//Property
    
    public string Description;//Field
}

一般情況

People people = new People();
people.Id = 123;
people.Name ="Lucy";
people.Description ="高級班";

反射寫法

Type type =typeof(People);
object oPeople = Activator.CreateInstance(type);
foreach(var item in type.GetProperties())
{
    Console.WriteLine(type.Name);
    Console.WriteLine(item.Name);
    Console.WriteLine(item.GetValue(oPeople));
    if(item.Name.Equals("Id"))
    {
        item.SetValue(oPeople,234);
    }else if(item.Name.Equals("Name"))
    {
        item.SetValue(oPeople,"風蕭蕭");
    }

}
foreach(var item in type.GetFields())
{
    Console.WriteLine(type.Name);
    Console.WriteLine(item.Name);
    Console.WriteLine(item.GetValue(oPeople));
    if(item.Name.Equals("Description"))
    {
        item.SetValue(oPeople,"昕學員");
    }
}

反射好處和限制

反射優點:動態
反射缺點:
1.寫起來複雜
2.避開編譯器的檢查
3.效能問題

GitHub範例

關於反射破壞單力模式、反射工廠封裝、反射泛型、反射黑科技=> 使用私有方法之後會專門寫一篇文章跟大家講解

參考資料

微軟 Reflection (C#)

本篇已同步發表至個人部落格
https://moushih.com/2022ithome08/


上一篇
玩轉C#之【泛型】
下一篇
玩轉C#之【特性(attribute)】
系列文
玩轉C# 進階學習之旅31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
小哈片刻
iT邦研究生 5 級 ‧ 2022-09-08 09:21:27

這標題... 不妥吧~ /images/emoticon/emoticon16.gif

隱士者 iT邦新手 4 級 ‧ 2022-09-08 13:57:13 檢舉

我在模擬當寫程式寫不出來的時候,又剛好在寫反射,就會很憤怒的說出 射爆妳 /images/emoticon/emoticon05.gif

我要留言

立即登入留言